package com.OjSystem.system.service.Impl;

import com.OjSystem.common.core.errorCode.modules.ojSystem.ServiceErrorCode;
import com.OjSystem.common.core.result.CommonResult;
import com.OjSystem.common.security.Enum.LoginUserEnum;
import com.OjSystem.common.security.service.TokenService;
import com.OjSystem.system.domain.SysUser;
import com.OjSystem.system.mapper.SysUserMapper;
import com.OjSystem.system.service.ISysUserService;
import com.OjSystem.system.utils.BCryptUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;

    /**
     * 管理员登录
     * @param userAccount
     * @param password
     * @return
     */
    @Override
    public CommonResult<String> login(String userAccount, String password) {
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("user_account", userAccount);
        SysUser sysUser = sysUserMapper.selectOne(sysUserQueryWrapper);

        if (sysUser == null) {
            return CommonResult.fail(ServiceErrorCode.USER_IS_NOT_EXIST);
        }

        if (!BCryptUtils.matchesPassword(password, sysUser.getPassword())) {
            return CommonResult.fail(ServiceErrorCode.PASSWORD_IS_ERROR);
        }

        // 获取token
        String token = tokenService.createToken(sysUser.getUserId(), LoginUserEnum.ADMIN.getCode());

        return CommonResult.success(token);
    }
}
